package com.bw.zyk.zhanggm.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.bw.zyk.zhanggm.gateway.config.IgnoreWhiteProperties;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;

@Component
public class AuthFiler implements GlobalFilter, Order {

    @Autowired
    RedisService redisService;

    @Autowired
    IgnoreWhiteProperties ignoreWhiteProperties;


    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        if (ignoreWhiteProperties.getWhites().contains(path)) {
            return chain.filter(exchange);
        }
        String token = exchange.getRequest().getHeaders().getFirst("Token");
        AjaxResult ajaxResult = AjaxResult.error(401, "请重新登录");
        if (token == null || !redisService.hasKey("login:" + token)) {
            return ServletUtils.webFluxResponseWriter(exchange.getResponse(), JSON.toJSONString(ajaxResult));
        }
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            return ServletUtils.webFluxResponseWriter(exchange.getResponse(), JSON.toJSONString(ajaxResult));
        }
        return chain.filter(exchange);
    }

    @Override
    public int value() {
        return 0;
    }
}
